package controllers

import (
	"backend/models"
	"backend/services"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type PermissionControl struct {
	services *services.PermissionServices
}

type PermissionForm struct {
	Name   string `json:"name"`
	Path   string `json:"path"`
	Action string `json:"action"`
	MenuId uint   `json:"menu_id"`
	Method string `json:"method"`
}
type PermissionResp struct {
	Id       uint   `json:"id"`
	Name     string `json:"name"`
	Path     string `json:"path"`
	MenuId   uint   `json:"menu_id"`
	Action   string `json:"action"`
	Method   string `json:"method"`
	MenuName string `json:"menu_name"`
}

func NewPermissionControl(s *services.PermissionServices) *PermissionControl {
	return &PermissionControl{services: s}
}

func (p *PermissionControl) Create(c *gin.Context) {
	var body *PermissionForm
	if err := c.ShouldBindJSON(&body); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
		return
	}
	data := models.Permission{
		Name:   body.Name,
		Path:   body.Path,
		Action: body.Action,
		MenuId: uint(body.MenuId),
		Method: body.Method,
	}
	if err := p.services.Create(&data); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"err": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "message": "success", "data": PermissionResp{
		Id:     data.ID,
		Name:   data.Name,
		Method: data.Method,
		Action: data.Action,
		MenuId: data.MenuId,
		Path:   data.Path,
	}})

}

func (p *PermissionControl) Update(c *gin.Context) {

}

func (p *PermissionControl) Delete(c *gin.Context) {

}

func (p *PermissionControl) GetPermissionList(c *gin.Context) {
	pageInfo, err := models.GetPageInfo(c)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
		return
	}
	filter := models.Permission{
		Name:   c.Query("name"),
		Action: c.Query("action"),
		Method: c.Query("method"),
		Path:   c.Query("path"),
	}
	menuidvalue := c.Query("menu_id")
	if menuidvalue != "" {
		menu_id, err := strconv.Atoi(menuidvalue)
		if err != nil || menu_id < 1 {
			c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
			return
		}
		filter.MenuId = uint(menu_id)
	}

	permissions, total, err := p.services.GetPermissionList(pageInfo, &filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"err": err.Error()})
		return
	}
	resp := []PermissionResp{}
	for _, item := range permissions {
		resp = append(resp, PermissionResp{
			Name:     item.Name,
			Path:     item.Path,
			Action:   item.Action,
			MenuId:   item.MenuId,
			Id:       item.ID,
			Method:   item.Method,
			MenuName: item.Menu.Name,
		})
	}
	c.JSON(http.StatusOK, gin.H{"message": "success", "code": 200, "data": resp, "page": pageInfo.Page, "size": pageInfo.Size, "total": total})

}
